# -*- coding:utf-8 -*-
# @Time : 2022/2/9 下午4:11 
# @Author : zdy
# @File : DeviceBase.py
# desc:
import os

from importQT import *
from Class.VoltSignal import dataBase, VoltSignal, DBResult
from enum import Enum

class SampleMode(Enum):
    ModeSampling = 1
    ModeProcess =2
    ModeManual =3

class ChannelInfo(object):
    def __init__(self):
        self.average = 0  # 记录原始信号的基准电压
        self.stable = 0
        self.data = []  # 存放定长原始信号基线数据
        self.dac = 0  # 存放基线调零时，上一次的输出
        self.average0 = 0 #记录调零后信号的均值
        self.data0 = [] #存放定长调零后信号，用于计算均值


class BaseData(object):
    def __init__(self):
        self.channels = []
        for i in range(dataBase.maxChannel):
            self.channels.append(ChannelInfo())
        self.isStable = False
        self.isTest = True  # True 调零
        self.isRunning = True  # False时，基线不调零、不计算均值、不刷新界面
        self.forceAnalyse = False  # 强制分析
        self.needZero = []
        self.convertZero = []   #调零转换，用于不调零红外
        self.PID = []
        self.ek = []
        self.ei = []
        self.ed =[]

    def enableTest(self):
        """开始基线调零"""
        self.isTest = True

    def disableTest(self):
        """停止基线调零"""
        self.isTest = False

    def start(self):
        self.isRunning = True

    def stop(self):
        self.isRunning = False


class SampleInfo(object):
    def __init__(self, name='', num=0, weight=0.0, flux=0.0):
        self.sampleId = None
        self.sampleName = name
        self.sampleNum = num
        self.sampleWeight = weight
        self.fluxWeight = flux
        self.vs = VoltSignal()
class MonitorONH(object):
    def __init__(self):
        # <editor-fold desc="DI">
        self.furnaceStatus = False#True 关
        self.waterStatus = False
        # </editor-fold>
        # <editor-fold desc="AD">
        self.current = 0.0
        self.volt = 0.0
        self.power = 0.0
        self.carrierflow = 0.0
        self.carrierpressure = 0.0
        self.waterT = 0.0
        self.waterpressure = 0.0
        self.waterspeed = 0.0
        self.purification = 0.0
        self.reformer = 0.0
        # </editor-fold>
        self.errorvolt = False
        self.errorCurrent = False
        self.errorwaterT = False
        self.errorwaterF = False
        self.errorcarrierpressure = False
        self.errorcarrier = False
        self.errorpurification = False
        self.errorreformer = False

class Monitor(object):
    def __init__(self):

        # True 升炉状态
        self.DILiftFurnace = False
        # True 炉刷复位
        self.DIBrush = False
        self.ADPressure = 0.0
        self.ADFlow = 0
        self.ReformerT = 0.0
        self.errorcarrierpressure = False
        self.errorcarrier = False

class Userparam(Enum):
    Current = 1
    Volt = 2
    WaterT =3
    Reformer = 4
    Purification =5
    GasPressure = 6
    Folw = 7
    Initcurrent = 8
    Initvolt  = 9
    Waterspeed = 10
    Waterpressure = 11

class PIU(object):
    def __init__(self, sU = 0.0):
        self.status = 0
        self.setU = sU
        self.readI = 0
        self.readU = 0
        self.realI = 0
        self.realU = 0

class DeviceBase(QObject):
    sigBaseLineUpdate = pyqtSignal(list)  # 由基线控件处理后的基线数据
    sigStatusTip = pyqtSignal(str)
    sigCurveLineAddPoint = pyqtSignal(int, float, float)
    '''触发主界面刷新结果的信号'''
    sigUpdateNewResult = pyqtSignal(DBResult)
    sigWaitting = pyqtSignal(int)
    sigSetStartEnable = pyqtSignal(bool)
    sigSetOnlyStartEnable = pyqtSignal(bool)
    sigClearWeight = pyqtSignal()
    sigStatusUpdate = pyqtSignal(Monitor)#仪器状态信号
    sigMonitorUpdate = pyqtSignal(MonitorONH)

    def __init__(self):
        super().__init__()
        pass

    def deinit(self):
        """将方法二进制序列化到文件"""
        # self.savesystemconfig()
        self.saveconfig()

    def saveconfig(self):
        """序列化方法到文件，并记录当前方法名"""
        pass

    def savesystemconfig(self):
        """序列化系统配置到文件"""
        pass

    def init(self):
        # self.getsystemconfig()
        pass

    def getsystemconfig(self):
        """反序列化得到系统配置"""
        pass

    def getconfig(self, name):
        """
        反序列化方法文件
        :param name:
        :return: 方法对象，序列化失败或者文件不存在，返回None
        """
        pass

    def baselineControl(self, pts):
        '''基线处理：判断稳定、求均值、调零,释放基线更新信号'''
        pass

    def baselineCheckStability(self):
        '''判断基线是否稳定：在指定时间内，都处于偏差范围内'''
        pass

    # <editor-fold desc="数据操作">

    # </editor-fold>

    # <editor-fold desc="分析时序">
    def analyseStart(self, sampleInfo, sampleMode = SampleMode.ModeSampling):
        pass

    def obtainResult(self):
        pass

    def taskNewSeq(self):
        pass

    def acq(self):
        """采集"""
        pass

    def dataupdate(self, data):
        pass

    # </editor-fold>

    # <editor-fold desc="仪器操作">
    def hfPowerOperation(self):
        """根据高频灯丝当前状态，取反操作，返回当前状态"""
        return False

    def preHeatHFPower(self):
        """等待高频灯丝预热300s"""
        pass

    def finishHFPower(self):
        """关闭高频灯丝，如果再执行等待预热，则结束预热"""
        pass

    def reset(self):
        """复位时，停止高频预热，降炉，设置流量"""
        pass

    def taskOpenLance(self, t):
        '''延迟t秒后再开启氧枪'''
        pass

    def taskCloseChamber(self, t):
        """延迟关闭炉室"""
        pass

    def regulatePID(self):
        '''高频控制'''
        pass

    def closePID(self):
        '''关闭高频'''
        pass

    def close_card(self):
        pass

    def link_card(self):
        pass

    def cardGetDO(self, index):
        """返回指定DO的当前输出值"""
        return False

    def cardOpenValve(self, *index):
        pass

    def cardCloseValve(self, *index):
        pass

    def cardAO(self, index, value, delay = True):
        pass

    def cardOutput(self):
        pass

    def initGas(self):
        """开机初始化仪器状态"""
        pass

    def flowregulate(self, isopen=True):
        '''流量控制'''
        pass

    def checkFurnaceLift(self):
        '''检查升炉状态，升炉，返回True'''
        return False

    def openGas(self):
        return False

    def openCarriergas(self):
        return False

    def checkPneumatic(self):
        return False

    def furnaceOperation(self, down=False):
        pass

    def tipAndSleep(self, s, time=0):
        """
        触发sigStatusTip信号，延迟time*1000s
        :param s:传递的信息
        :param time:延迟时间，单位s,默认不延迟
        """
        pass

    def exhausterOperation(self):
        pass

    def downFurnace(self):
        '''降炉操作'''
        pass
    # </editor-fold>

    def addResult(self,model, r):
        """模型中添加result"""
        model.beginResetModel()
        rowIndex = model.rowCount()
        model.beginInsertRows(QModelIndex(), rowIndex, rowIndex)
        model.insertRow(rowIndex)
        model.endInsertRows()
        self.setupRow(model, rowIndex, r)
        model.endResetModel()

    def addResults(self, model, rs):
        for r in rs:
            self.addResult(model, r)

    def setupRow(self, model, row, r):
        pass

    def updateResults(self, rs):
        '''
        更新model中的数据：遍历mmodel所有行，找到匹配的id，对应更新该行数据
        :param rs:list[DBResult]
        :return:
        '''
        rowcount = self.modelResult.rowCount()
        if rowcount > 0:
            for i in range(0, rowcount):
                id = self.modelResult.item(i, 0).data(0)
                items = list(filter(lambda x: x.SampleId.strftime("%Y-%m-%d %H:%M:%S") == id, rs))
                if len(items) == 1:
                    self.setupRow(self.modelResult, i, items[0])
